<?php

namespace App\Http\Controllers;

use App\Http\Requests\CreatePostForm;
use App\Inspections\Spam;
use App\Reply;
use App\Thread;

class RepliesController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth')->except(['index']);
    }

    /**
     * Display a listing of the resource.
     *
     * @param        $channelId
     * @param Thread $thread
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index($channelId, Thread $thread)
    {
        return $thread->replies()->paginate(20);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param                $channelId
     * @param Thread         $thread
     * @param CreatePostForm $form
     * @return mixed
     */
    public function store($channelId, Thread $thread, CreatePostForm $form)
    {
        if ($thread->locked) {
            return response('Thread is locked.', 422);
        }
        $reply = $thread->addReply([
            'body'    => request('body'),
            'user_id' => auth()->id(),
        ]);

        return $reply->load('owner');//预加载owner
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Reply $reply
     * @param Spam        $spam
     * @return mixed
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(Reply $reply, Spam $spam)
    {
        $this->authorize('update', $reply);
        request()->validate(['body' => 'required|spamfree']);
        $reply->update(request(['body']));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Reply $reply
     * @return \Illuminate\Http\Response
     */
    public function destroy(Reply $reply)
    {
        $this->authorize('update', $reply);

        $reply->delete();
        if (request()->expectsJson()) {
            return response((['status' => 'Reply deleted']));
        }

        return back();
    }

    /**
     * @param Spam $spam
     */
    protected function validateReply(Spam $spam): void
    {
        $this->validate(request(), ['body' => 'required|spamfree']);
    }
}
